package com.wanlian.dao.impl;

import com.wanlian.common.PageCondition;
import com.wanlian.common.RankType;
import com.wanlian.dao.*;
import com.wanlian.entity.*;
import com.wanlian.error.SuccessCode;
import com.wanlian.model.ResultModel;
import com.wanlian.sql.SqlUtil;
import com.wanlian.util.DateUtil;
import com.wanlian.util.StringUtil;
import com.wanlian.vo.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.support.TaskUtils;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Component
public class UserTaskDaoImpl extends GenericDaoImpl<UserTask> implements UserTaskDao {

    public UserTaskDaoImpl() {
        super(UserTask.class);
    }

    @Autowired
    private UserScoreDao userScoreDao;

    @Autowired
    private TaskDao taskDao;

    @Autowired
    private ScoreHistoryDao scoreHistoryDao;

    @Override
    public ResultModel queryUserTasks(PageCondition conditions) {
        StringBuffer sqlWhere = new StringBuffer(" where 1=1");
        ArrayList<Object> param = new ArrayList<Object>();

        if (conditions.isEmpty("userId")) {
            int userId = Integer.parseInt((String) conditions.getByKey("userId"));
            sqlWhere.append(" and userId =? ");
            param.add(userId);
        }
        if (conditions.isEmpty("taskId")) {
            int taskId = Integer.parseInt((String) conditions.getByKey("taskId"));
            sqlWhere.append(" and taskId =? ");
            param.add(taskId);
        }
        if (conditions.isEmpty("startTime")&&conditions.isEmpty("endTime")) {
            String startTime = (String) conditions.getByKey("startTime");
            String endTime = (String) conditions.getByKey("endTime");
            sqlWhere.append(" and addTime between date(?) and date(?) ");
            param.add(startTime);
            param.add(endTime);
        }

        List<UserTask> lists = new ArrayList<UserTask>();
        String hql = String.format("from %s order by addtime desc  " + sqlWhere, entityClassName());
        lists = this.queryForListByPage(hql, param.toArray(), conditions.getPage());
        String countSql = String.format("select count(*) from %s" + sqlWhere, entityClassName());
        long count = this.queryCount(countSql, param.toArray());
        ResultModel resultModel = new ResultModel(true, lists, count);
        return resultModel;
    }

    @Override
    public ResultModel delUserTasks(UserTask userTask) {

        ResultModel resultModel = new ResultModel();
        UserTask userTask1 = this.queryById(userTask.getId());
        if (userTask1 != null) {
            this.delete(userTask.getId());
            resultModel.setBresult(true);
        } else {
            resultModel.setBresult(false);
            resultModel.setMessage("未找到任务");
        }
        return resultModel;

    }

    @Override
    public ResultModel addUserTask(UserTask userTask) {
        ResultModel resultModel = new ResultModel();
        userTask.setAddTime(DateUtil.currentTimestamp());
        this.add(userTask);
        resultModel.setBresult(true);
        resultModel.setMessage(SuccessCode.SUCCESS_ADD);

        Task task = taskDao.queryById(userTask.getTaskId());
        //添加按rankType分为两种积分类型，即一个用户两条分数表加以区分
        UserScore userScoreD = userScoreDao.queryUserScoreByParams(userTask.getUserId(),RankType.Rank_INIT);
        UserScore userScoreI = userScoreDao.queryUserScoreByParams(userTask.getUserId(),RankType.RANK_INT);

        double scored=task.getRank()*4/10;
        double scorei=task.getRank()*6/10;

        //分数表为空则向分数表添加数据，不为空则叠加分数
        if (userScoreD == null) {
            UserScore userScoredb = new UserScore();
            userScoredb.setModifyTime(DateUtil.currentDateTimestamp());
            userScoredb.setScore(scored);
            userScoredb.setUserId(userTask.getUserId());
            userScoredb.setRankType(RankType.Rank_INIT);
            userScoreDao.add(userScoredb);
        } else {
            userScoreD.setModifyTime(DateUtil.currentTimestamp());
            userScoreD.setScore(userScoreD.getScore() + scored);
            userScoreDao.update(userScoreD);
        }

        if (userScoreI == null) {
            UserScore userScoredb = new UserScore();
            userScoredb.setModifyTime(DateUtil.currentDateTimestamp());
            userScoredb.setScore(scorei);
            userScoredb.setUserId(userTask.getUserId());
            userScoredb.setRankType(RankType.RANK_INT);
            userScoreDao.add(userScoredb);
        } else {
            userScoreI.setModifyTime(DateUtil.currentTimestamp());
            userScoreI.setScore(userScoreI.getScore() + scorei);
            userScoreDao.update(userScoreI);
        }



        //插入历史记录表
        ScoreHistory scoreHistory = new ScoreHistory();
        scoreHistory.setAddTime(DateUtil.currentTimestamp());
        scoreHistory.setTaskId(userTask.getTaskId());
        scoreHistory.setScore(task.getRank());
        scoreHistory.setUserId(userTask.getUserId());
        scoreHistory.setHasAddUserScore(true);
       // scoreHistory.setRankType(task.getRankType());
        scoreHistoryDao.add(scoreHistory);
        return resultModel;
    }

    @Override
    public List<UserTask> queryUserTaskByTaskId(int  id) {
        String hql = String.format("from %s where taskId=?", entityClassName());
        List<UserTask> userTask =this.queryForList(hql, new Object[]{id}); //this.queryForObject(hql, new Object[]{id});
        return userTask;
    }

    @Override
    public ResultModel queryUserTaskByParams(PageCondition pageCondition) {
        String sql=" select t.id,u.username,u.phone,t.name,t.ranktype,t.rank,ut.addtime,iv.inviteuserid,iv.isbinddevice,iv.isbindint,iv.registertime,iv.iscompleted,iv.phone as invitephone" +
                " from tb_user u,tb_task t,tb_usertask ut,tb_invite iv  where ut.taskid=t.id and ut.userid=u.id and iv.userid=ut.userid ";
        StringBuilder sqlWhere=new StringBuilder();
        String[] column = {"id","username", "phone", "name", "rankType", "rank", "addtime","inviteuserid","isbinddevice","isbindint","registertime","iscompleted","invitephone"};
        ArrayList<Object> param = new ArrayList<Object>();
        if (pageCondition.isEmpty("username")) {
            String username = (String) pageCondition.getByKey("username");
            sqlWhere.append(" and u.username like ?");
            param.add("%" + username + "%");
        }
        if (pageCondition.isEmpty("rankType")) {
            int rankType = Integer.parseInt((String) pageCondition.getByKey("rankType"));
            sqlWhere.append(" and t.rankType=?");
            param.add(rankType);
        }
        if (pageCondition.isEmpty("name")) {
            String name = (String) pageCondition.getByKey("name");
            sqlWhere.append(" and t.name=?");
            param.add(name);
        }
        if (pageCondition.isEmpty("startTime")&&pageCondition.isEmpty("endTime")) {
            String startTime = (String) pageCondition.getByKey("startTime");
            String endTime = (String) pageCondition.getByKey("endTime");
            sqlWhere.append(" and ut.addtime between date(?) and date(?) ");
            param.add(startTime);
            param.add(endTime);
        }
        List<Map<String, Object>> lists = this.queryForListObjectByPage(sql+sqlWhere + " order by addtime desc  ", param.toArray(), pageCondition.getPage(), column);
        int count =this.queryCountByParam("select count(1)from tb_user u,tb_task t,tb_usertask ut where ut.taskid=t.id and ut.userid=u.id "+sqlWhere,param.toArray());
        ResultModel resultModel = new ResultModel(true, lists, count);
        return resultModel;

    }
}
